import React,{Component,View,StyleSheet,Text,ListView} from 'react-native';
import Farm from './farm';

//reduce
import {bindActionCreators} from 'redux';
import * as mainScreenActions from '../../actions/mainScreenActions';
import { connect } from 'react-redux';


class farmlist extends Component {
  static propTypes = {
  };
  //==========================构造函数=================================================
  constructor(props) {
    super(props);
    //存放list的引用
    this.mylist=[];
    this.selectItemIndex=0;//被选中的list项目初始是0
  }
  //=========================首次render后===================================================
  componentDidMount(){
    //默认选中第一个
    this.mylist[this.selectItemIndex].toSelectState();
  }
  //======================选择每一个list时的回调================================================
  _selectItem = (index)=>{
    if (index==this.selectItemIndex) {
      return;
    }else{
      this.mylist[this.selectItemIndex].toNoSelectState();
      this.mylist[index].toSelectState();
      this.selectItemIndex=index;
    } 
  };
  //=======================渲染==============================================================
  render() {
    var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    return (
      <ListView
        style={styles.contain}
        dataSource={ds.cloneWithRows(this.props.reduxFarmlist)}
        renderRow={(rowData,sec,index) => <Farm
                                            reduxSelectfarm={this.props.reduxSelectfarm}
                                            ref={(row) =>{this.mylist[index]=row;}}
                                            farmname={rowData} 
                                            index={index} 
                                            selectItem={this._selectItem}>
                                          </Farm>} 
        //renderHeader={(e)=>this._renderHeader(e)}
      />
        
    );
  }
}

const styles = StyleSheet.create({
  contain:{
    flex:1,
    //backgroundColor:'red',

  }
});

//将全局state绑定到组件的props中
function mapStateToProps(state) {
  return { 
    reduxFarmlist:state.mainScreenRedux.mainscreen.farmlistDetail
  }
}

//绑定一个方法到props中
function mapDispatchToProps(dispatch) {
  var mapaction=bindActionCreators(mainScreenActions, dispatch);
  return {
    reduxSelectfarm:mapaction.reduxSelectfarm,
  }
}

//将全局的state绑定到组件中
export default connect(mapStateToProps,mapDispatchToProps)(farmlist);